﻿using Jugg.Core.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Jugg.Mapping.Setting;
using Jugg.Core.Caching;
using Jugg.Mapping;

namespace Jugg.Services.Setting
{
    public class SettingService : ISettingService
    {
        private const string MODEL_KEY = "Sniper.service.setting";
        private IRepository<Entities.Setting> _settingRepository;
        private ICacheManager _cacheManager;
        public SettingService(IRepository<Entities.Setting> settingRepository,
            ICacheManager cacheManager)
        {
            this._settingRepository = settingRepository;
            this._cacheManager = cacheManager;
        }

        /// <summary>
        /// 获取所有数据并缓存
        /// </summary>
        /// <returns></returns>
        public List<SettingMapping> getAllCache()
        {
            return _cacheManager.get(MODEL_KEY, () =>
            {
                var result = _settingRepository.Table.ToList();
                if (result.Any())
                    return result.Select(item => item.toModel()).ToList();
                return null;
            });
        }

        /// <summary>
        /// 通过名称获取
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public SettingMapping getByName(string name)
        {
            var list = getAllCache();
            if (list == null)
                return null;
            return list.FirstOrDefault(o => o.Name == name);
        }


        /// <summary>
        /// 保存设置数据
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        public SettingResult saveSetting(string name, string value)
        {
            SettingResult result = new SettingResult();
            var item = _settingRepository.Table.FirstOrDefault(o => o.Name == name);
            if (item == null)
            {
                item = new Entities.Setting() { Id = Guid.NewGuid(), Name = name, Value = value };
                _settingRepository.insert(item);
            }
            else
            {
                item.Value = value;
                _settingRepository.update(item);
            }
            result.Success = true;
            result.Message = "保存成功";
            _cacheManager.remove(MODEL_KEY);
            return result;
        }

    }
}
